package com.example.springbootyczy.filter;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 过滤器（filter）：属于servlet
 * 拦截器（intercepter）：属于springmvc
 */
@Slf4j
public class WebFilter1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init1: {}", "web过滤器被初始化");
    }

    /**
     * 过滤逻辑
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("doFilter1: {}", "开始过滤操作");
        //配置需要忽略的路径
        Set<String> ignorePaths = new HashSet<>(
                Arrays.asList("/login",
                                "/student/list"));
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        //获取请求路径
        String path = httpRequest.getRequestURI();
        log.info("reqeustUri: {}", path);
        //使用忽略配置的Set判断当前的请求是否包含其中，如果包含则放行
        if(ignorePaths.contains(path)){
            chain.doFilter(request, response);
        }else{
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("text/html;charset=utf-8");
            Map<String, String> result = new HashMap<String, String>();
            result.put("code", "1003");
            result.put("msg", "权限不足，情联系后台管理员！");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.println(JSONUtil.toJsonStr(result));
        }
    }

    @Override
    public void destroy() {
        log.info("init: {}", "web过滤器被销毁");
    }
}
